﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using System.Xml;
using KL.Store.Core;
using KL.Store.Core.Domain;
using _PosnetDotNetModule;
using KL.Store.Core.Domain.Enum;
using KL.Store.Core.iodeme;
using PayU.AutomaticLiveUpdate;
using PayU;

namespace KL.Store.Core.POS
{
    #region POSResult

    public class POSResult
    {
        public string ApproveCode { get; set; }
        public string ReturnCode { get; set; }
        public string Explanation { get; set; }
        public string Message { get; set; }
        public string RequestXMLString { get; set; }
        public string ResponseXMLString { get; set; }
        public string OrderID { get; set; }
    }

    #endregion

    #region Payment

    public class PaymentUtils
    {
        #region GetSHA1

        public string GetSHA1(string SHA1Data)
        {
            SHA1 sha = new SHA1CryptoServiceProvider();
            string HashedPassword = SHA1Data;
            byte[] hashbytes = Encoding.GetEncoding("ISO-8859-9").GetBytes(HashedPassword);
            byte[] inputbytes = sha.ComputeHash(hashbytes);
            return GetHexaDecimal(inputbytes);
        }

        #endregion

        #region GetHexaDecimal

        public string GetHexaDecimal(byte[] bytes)
        {
            StringBuilder s = new StringBuilder();
            int length = bytes.Length;
            for (int n = 0; n <= length - 1; n++)
            {
                s.Append(String.Format("{0,2:x}", bytes[n]).Replace(" ", "0"));
            }
            return s.ToString();
        }

        #endregion

        #region Send

        public POSResult Send(Pos aPos, string Email, string InstallmentCount, int AccountNo, string CCNumber, short ExpMonth, short ExpYear, string CVV, string CardOwnerName, decimal Amount, bool Use3D, string CAVV, string ECI, Address addres)
        {
            #region Vars

            string strMode = aPos.Mode;  //"TEST";  // "PROD";
            string strVersion = aPos.Version;// "v0.01";
            string strTerminalID = aPos.TerminalId; //"111995"; //8 Haneli TerminalID yazılmalı.
            string _strTerminalID = aPos.AddTerminalId + strTerminalID;
            string strProvUserID = aPos.ApiUserName;// "PROVAUT";
            string strProvisionPassword = aPos.ApiPass;// "123qweASD"; // "123qweASD"; //TerminalProvUserID şifresi
            //string _BrandID = "VISA";

            string strUserID = aPos.UserId; //"DENE"; // "XXXXXX";
            string strMerchantID = aPos.StoreNo;// "600218"; //Üye İşyeri Numarası
            string strIPAddress = Utils.UserIP; //Kullanıcının IP adresini alır
            string strEmailAddress = Email;//"info@tradesis.com";
            string strOrderID = "ORID" + AccountNo.ToString("000000") + Parameters.Now.Year.ToString("0000") + Parameters.Now.Month.ToString("00") + Parameters.Now.Day.ToString("00") + Parameters.Now.Hour.ToString("00") + Parameters.Now.Minute.ToString("00") + Parameters.Now.Second.ToString("00");

            string strNumber = CCNumber;
            string strExpireDate = ExpMonth.ToString("00") + (ExpYear > 2000 ? (ExpYear - 2000).ToString("00") : ExpYear.ToString("00"));
            string strCVV2 = CVV;

            string strAmount = Math.Floor(Amount * 100).ToString(); //İşlem Tutarı 1.00 TL için 100 gönderilmeli
            string strAmountWithDot = Amount.ToString().Replace(",", "."); //İşlem Tutarı 1.00 TL için 1.00 gönderilmeli
            string strAmount12 = Math.Floor(Amount * 100).ToString("000000000000"); //Vakıfbank için

            //string strType = "sales";
            string strCurrencyCode = "949"; // TL
            string strCardholderPresentCode = "0";
            //string strMotoInd = "N";
            string strInstallmentCount = InstallmentCount;
            string strInstallmentCountZero = InstallmentCount;
            string strInstallmentCountSpace = InstallmentCount;
            string strInstallmentDouble = Convert.ToInt32(InstallmentCount).ToString("00");

            if (InstallmentCount == "1")
            {
                strInstallmentCountZero = "0";
                strInstallmentCountSpace = "";
                strInstallmentDouble = "00";
            }

            string strHostAddress = aPos.ApiUrl;

            string SecurityData = GetSHA1(strProvisionPassword + _strTerminalID).ToUpper();
            string HashData = GetSHA1(strOrderID + strTerminalID + strNumber + strAmount + SecurityData).ToUpper();

            string strXML = aPos.XmlText;

            #endregion

            #region 3D Vars

            string _3DValidation = "";

            if (Use3D)
            {
                _3DValidation = aPos.XmlText3D.Replace("{CAVV}", CAVV);
            }

            #endregion

            #region XML Prepare

            if (strXML != "")
            {
                strXML = strXML.Replace("{Mode}", strMode).Replace("{Version}", strVersion);
                strXML = strXML.Replace("{HashData}", HashData).Replace("{UserID}", strUserID).Replace("{MerchantID}", strMerchantID);
                strXML = strXML.Replace("{IPAddress}", strIPAddress).Replace("{EmailAddress}", strEmailAddress).Replace("{CardNumber}", strNumber);
                strXML = strXML.Replace("{ExpireDate}", strExpireDate).Replace("{CVV2}", strCVV2).Replace("{OrderID}", strOrderID);
                strXML = strXML.Replace("{Installment}", strInstallmentCount).Replace("{InstallmentZero}", strInstallmentCountZero).Replace("{InstallmentSpace}", strInstallmentCountSpace).Replace("{InstallmentDouble}", strInstallmentDouble);
                strXML = strXML.Replace("{Amount}", strAmount).Replace("{AmountWithDot}", strAmountWithDot).Replace("{Amount12}", strAmount12);
                strXML = strXML.Replace("{CurrencyCode}", strCurrencyCode).Replace("{CardholderPresentCode}", strCardholderPresentCode);
                strXML = strXML.Replace("{TerminalID}", strTerminalID).Replace("{APIPass}", aPos.ApiPass).Replace("{CardType}", "VISA").Replace("{APIUser}", aPos.ApiUserName);
                strXML = strXML.Replace("{ExpireYear4}", ExpYear.ToString()).Replace("{ExpireMonth}", ExpMonth.ToString("00"));
                strXML = strXML.Replace("{ExpireYear2}", (ExpYear > 2000 ? (ExpYear - 2000).ToString("00") : ExpYear.ToString("00")));

                strXML = strXML.Replace("{CompanyAddress}", "").Replace("{CompanyCity}", "").Replace("{CompanyPostalCode}", "").Replace("{Phone}", "");
                strXML = strXML.Replace("{City}", "").Replace("{PostalCode}", "").Replace("{Address}", "").Replace("{CompanyName}", "").Replace("{Name}", "");
                strXML = strXML.Replace("{CAVV}", _3DValidation);
            }

            #endregion

            POSResult res = new POSResult();

            try
            {
                if (aPos.PosGroup == 4)
                {
                    #region use Arena payment
                    iodeme.AuthenticationInfo authinfo = new AuthenticationInfo();
                    authinfo.agentID = aPos.StoreNo;
                    authinfo.username = aPos.ApiUserName;

                    iodeme.iodeme arenapos = new iodeme.iodeme();
                    arenapos.AuthenticationInfoValue = authinfo;

                    var xactParams = new iodeme.xactParam();
                    xactParams.posID = aPos.TerminalId;
                    xactParams.bankID = aPos.UserId;
                    xactParams.amount = Amount;
                    xactParams.currency = "TRY";
                    xactParams.instalment = InstallmentCount == "1" ? 0 : int.Parse(InstallmentCount);
                    xactParams.cardholdername = CardOwnerName;
                    xactParams.cardexpiredate = new DateTime(ExpYear, ExpMonth, 01);
                    xactParams.cvc = CVV;
                    xactParams.cardno = CCNumber;
                    xactParams.email = Email;
                    xactParams.phone = "";
                    xactParams.clientip = "";

                    iodeme.xactParam[] possales = new iodeme.xactParam[] { xactParams };
                    try
                    {
                        var posresult = arenapos.Sales(possales);
                        if (posresult[0].result_text != "ERROR")
                        {

                            res.OrderID = strOrderID;
                            res.ApproveCode = "00";
                            res.Explanation = "İşlem Başarılı";
                        }
                        else
                        {
                            res.Explanation = "İşlem Başarısız - " + posresult[0].error_text;
                        }
                    }
                    catch (Exception ex)
                    {
                        res.Message = ex.Message;
                        res.ResponseXMLString = "";
                    }
                    #endregion
                }
                else if (aPos.PosGroup == 5)
                {
                    #region Payu Entegrasyon

                    PayU.Configuration.Instance
                   .SetSignatureKey(Parameters.PayuSignatureKey)
                   .SetEnvironment(Parameters.PayuEnvironment);

                    var order = new PayU.AutomaticLiveUpdate.OrderDetails();
                    order.Merchant = Parameters.PayuMerchantId;
                    order.OrderRef = strOrderID;
                    order.OrderDate = DateTime.Now;


                    var product1 = new PayU.AutomaticLiveUpdate.ProductDetails
                    {
                        Code = "PayuOdeme",
                        Name = "PayuOdeme",
                        Quantity = 1,
                        UnitPrice = Amount,
                        Information = "Payu Odeme"
                    };

                    order.ProductDetails.Add(product1);

                    order.CardDetails = new PayU.AutomaticLiveUpdate.CardDetails
                    {
                        CardNumber = CCNumber,
                        ExpiryMonth = ExpMonth.ToString(),
                        ExpiryYear = ExpYear.ToString(),
                        CVV = CVV,
                        CardOwnerName = CardOwnerName
                    };

                    if (addres != null)
                    {
                        var namesplit = addres.Name.Split(' ');
                        order.BillingDetails = new PayU.AutomaticLiveUpdate.BillingDetails
                        {

                            FirstName = namesplit[0],
                            LastName = namesplit[1],
                            Email = strEmailAddress,
                            PhoneNumber = addres.Phone,
                            CountryCode = "TR",
                        };

                    }

                    order.ClientIpAddress = strIPAddress;

                    try
                    {
                        var response = AluRequest.ProcessPayment(order);

                        if (response.Is3DSReponse)
                        {
                            //3d gerekiyor
                        }

                        if (response.Status == Status.Success)
                        {
                            res.OrderID = strOrderID;
                            res.ApproveCode = "00";
                            res.Explanation = "İşlem Başarılı";
                        }
                        else
                        {
                            res.Explanation = "İşlem Başarısız - " + response.ReturnMessage;
                        }
                    }
                    catch (PayuException ex)
                    {
                        res.Explanation = "İşlem Başarısız - " + ex.Message;
                    }


                    #endregion
                }
                else
                {
                    #region Request

                    res.RequestXMLString = strXML;

                    if (!string.IsNullOrEmpty(aPos.VarType))
                    {
                        strXML = aPos.VarType + "=" + strXML;
                    }

                    WebRequest _WebRequest = WebRequest.Create(strHostAddress);
                    _WebRequest.Timeout = 300000;  //300 sec = 5 min
                    _WebRequest.Method = aPos.SendType; // "POST";  GET / POST db den alınıyor

                    byte[] byteArray = Encoding.UTF8.GetBytes(strXML);
                    _WebRequest.ContentType = "application/x-www-form-urlencoded";
                    _WebRequest.ContentLength = byteArray.Length;

                    Stream dataStream = _WebRequest.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();

                    WebResponse _WebResponse = _WebRequest.GetResponse();
                    dataStream = _WebResponse.GetResponseStream();

                    StreamReader reader = new StreamReader(dataStream);
                    string responseFromServer = reader.ReadToEnd();

                    #endregion

                    #region Response

                    res.ResponseXMLString = responseFromServer;

                    //GVPSResponse XML'in değerlerini okuyoruz. İstediğiniz geri dönüş değerlerini gösterebilirsiniz.
                    string XML = responseFromServer;
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.LoadXml(XML);

                    #region ApproveCode

                    if (!string.IsNullOrEmpty(aPos.ApproveXMLKey))
                    {
                        try
                        {
                            XmlElement xElement1 = xDoc.SelectSingleNode(aPos.ApproveXMLKey) as XmlElement;
                            if (string.IsNullOrEmpty(aPos.ApproveAttribute))
                            {
                                res.ApproveCode = xElement1.InnerText;
                            }
                            else
                            {
                                res.ApproveCode = xElement1.Attributes[aPos.ApproveAttribute].Value.ToString();
                            }
                        }
                        catch
                        {

                        }
                    }

                    #endregion

                    #region ReasonCode

                    if (!string.IsNullOrEmpty(aPos.ReasonXMLKey))
                    {
                        try
                        {
                            XmlElement xElement1 = xDoc.SelectSingleNode(aPos.ReasonXMLKey) as XmlElement;
                            if (string.IsNullOrEmpty(aPos.ReasonAttribute))
                            {
                                res.ReturnCode = xElement1.InnerText;
                            }
                            else
                            {
                                res.ReturnCode = xElement1.Attributes[aPos.ReasonAttribute].Value.ToString();
                            }
                        }
                        catch
                        {

                        }
                    }

                    #endregion

                    #region ErrorMsg

                    if (!string.IsNullOrEmpty(aPos.ErrMsgXMLKey))
                    {
                        try
                        {
                            XmlElement xElement3 = xDoc.SelectSingleNode(aPos.ErrMsgXMLKey) as XmlElement;
                            if (string.IsNullOrEmpty(aPos.ErrMsgAttribute))
                            {
                                res.Message = xElement3.InnerText;
                            }
                            else
                            {
                                res.Message = xElement3.Attributes[aPos.ErrMsgAttribute].Value.ToString();
                            }
                        }
                        catch
                        {

                        }
                    }
                    else
                    {
                        res.Message = res.ReturnCode;
                    }

                    #endregion

                    //00 ReasonCode döndüğünde işlem başarılıdır. Müşteriye başarılı veya başarısız şeklinde göstermeniz tavsiye edilir. (Fraud riski)
                    if (res.ApproveCode == aPos.ApproveCode)
                    {
                        res.OrderID = strOrderID;
                        res.Explanation = "İşlem Başarılı";
                    }
                    else
                    {
                        res.Explanation = "İşlem Başarısız";
                    }

                    #endregion
                }

            }
            catch (Exception ex)
            {
                res.Message = ex.Message;
                res.ResponseXMLString = "";
            }

            return res;
        }

        #endregion

        #region Start3D

        public string Start3D(Pos aPos, string Email, string SessionId, string TimeStamp, string OrderId, string InstallmentCount, int AccountNo, string CCNumber, short ExpMonth, short ExpYear, string CVV, string CardOwnerName, decimal Amount, Address addres)
        {
            #region Vars

            CreditCardTypeType? ccType = CreditCard.GetCardTypeFromNumber(CCNumber);

            int creditCardType = 0;
            if (ccType == CreditCardTypeType.Visa)
            {
                creditCardType = 1;
            }
            else if (ccType == CreditCardTypeType.MasterCard)
            {
                creditCardType = 2;
            }

            string strMode = aPos.Mode;  //"TEST";  // "PROD";
            string strVersion = aPos.Version;// "v0.01";
            string strTerminalID = aPos.TerminalId; //"111995"; //8 Haneli TerminalID yazılmalı.
            string _strTerminalID = aPos.AddTerminalId + strTerminalID;
            string strProvUserID = aPos.ApiUserName;// "PROVAUT";
            string strProvisionPassword = aPos.ApiPass;// "123qweASD"; // "123qweASD"; //TerminalProvUserID şifresi
            //string _BrandID = "VISA";

            string strUserID = aPos.UserId; //"DENE"; // "XXXXXX";
            string strMerchantID = aPos.StoreNo;// "600218"; //Üye İşyeri Numarası
            string strIPAddress = Utils.UserIP; //Kullanıcının IP adresini alır
            string strEmailAddress = Email;//"info@tradesis.com";

            string strExpireMonth = ExpMonth.ToString("00");
            string strExpireDate = strExpireMonth + (ExpYear > 2000 ? (ExpYear - 2000).ToString("00") : ExpYear.ToString("00"));
            string strExpireYear2 = (ExpYear > 2000 ? (ExpYear - 2000).ToString("00") : ExpYear.ToString("00"));

            string strAmount = Math.Floor(Amount * 100).ToString(); //İşlem Tutarı 1.00 TL için 100 gönderilmeli
            string strAmountWithDot = Amount.ToString().Replace(",", "."); //İşlem Tutarı 1.00 TL için 1.00 gönderilmeli
            string strAmount12 = Math.Floor(Amount * 100).ToString("000000000000"); //Vakıfbank için

            //string strType = "sales";
            string strCurrencyCode = "949"; // TL
            string strCardholderPresentCode = "0";
            //string strMotoInd = "N";
            string strInstallmentCount = InstallmentCount;
            string strInstallmentCountZero = InstallmentCount;
            string strInstallmentCountSpace = InstallmentCount;
            string strInstallmentDouble = Convert.ToInt32(InstallmentCount).ToString("00");

            if (InstallmentCount == "1")
            {
                strInstallmentCountZero = "0";
                strInstallmentCountSpace = "";
                strInstallmentDouble = "00";
            }

            string strHostAddress = aPos.ApiUrl3D;

            string successURL;
            string failURL;

            string urlPRefix = HttpContext.Current.Request.Url.Scheme + System.Uri.SchemeDelimiter + HttpContext.Current.Request.Url.Host;

            successURL = urlPRefix + "/Cart/BankSuccess/" + aPos.PosId.ToString();
            failURL = urlPRefix + "/Cart/BankFail/" + aPos.PosId.ToString();

            //   successURL = successURL.Replace("localhost", "localhost:10415");
            // failURL = failURL.Replace("localhost", "localhost:10415");

            string formStr = aPos.Form3D;

            #region Vakıf Hash
            //string hashStr = uyeno + kkno + gectar + tutar + dcins + sipbil + sesbil + burl + hurl + zaman + xcip;
            string hashStr = strMerchantID + CCNumber + strExpireYear2 + strExpireMonth + strAmountWithDot + "949" + OrderId + SessionId + successURL + failURL + TimeStamp + strUserID;
            string strSummary = Security.CreateHash(hashStr);

            #endregion

            #region Garanti Hash

            string SecurityData = GetSHA1(strProvisionPassword + _strTerminalID).ToUpper();
            string HashData = GetSHA1(OrderId + strTerminalID + CCNumber + strAmount + SecurityData).ToUpper();

            #endregion

            #endregion

            #region Form Prepare


            // arena
            if (aPos.PosGroup == 4)
            {

                ArenaHelper helper = new ArenaHelper();
                return formStr = helper.Inputs(aPos.StoreNo, aPos.ApiUserName, "https://www.paynet.com.tr/connact/iodeme.asmx", aPos.UserId, aPos.TerminalId, CCNumber, CardOwnerName, int.Parse(InstallmentCount), Amount, "TRY", ExpYear, ExpMonth, 1, CVV, Email, "", "", successURL);


            }
            if (aPos.PosGroup == 5)
            {
                #region Payu Entegrasyon

                PayU.Configuration.Instance
               .SetSignatureKey(Parameters.PayuSignatureKey)
               .SetEnvironment(Parameters.PayuEnvironment);

                var order = new PayU.AutomaticLiveUpdate.OrderDetails();
                order.Merchant = Parameters.PayuMerchantId;
                order.OrderRef = OrderId;
                order.OrderDate = DateTime.Now;


                var product1 = new PayU.AutomaticLiveUpdate.ProductDetails
                {
                    Code = "PayuOdeme",
                    Name = "PayuOdeme",
                    Quantity = 1,
                    UnitPrice = Amount,
                    Information = "Payu Odeme"
                };

                order.ProductDetails.Add(product1);

                order.CardDetails = new PayU.AutomaticLiveUpdate.CardDetails
                {
                    CardNumber = CCNumber,
                    ExpiryMonth = ExpMonth.ToString(),
                    ExpiryYear = ExpYear.ToString(),
                    CVV = CVV,
                    CardOwnerName = CardOwnerName
                };

                if (addres != null)
                {
                    var namesplit = addres.Name.Split(' ');
                    order.BillingDetails = new PayU.AutomaticLiveUpdate.BillingDetails
                    {

                        FirstName = namesplit[0],
                        LastName = namesplit[1],
                        Email = strEmailAddress,
                        PhoneNumber = addres.Phone,
                        CountryCode = "TR",
                    };

                }

                order.ClientIpAddress = strIPAddress;


                var response = AluRequest.ProcessPayment(order);

                if (response.Is3DSReponse)
                {
                    successURL = urlPRefix + "/Cart/BankSuccess/" + aPos.PosId.ToString();
                    HttpContext.Current.Response.Redirect(successURL);
                }

                #endregion
            }
            // YKB
            if (aPos.PosGroup == 2)
            {
                EventView = "";
                Boolean result = false;
                C_Posnet posnetObj = new C_Posnet();
                posnetObj.SetURL(aPos.ApiUrl3D);
                posnetObj.SetMid(aPos.StoreNo);
                posnetObj.SetTid(aPos.TerminalId);

                result = posnetObj.DoSaleTran(CCNumber, strExpireYear2 + strExpireMonth, CVV, OrderId, strAmount, "YT", strInstallmentDouble, "", "");
                EventView += "XML Request : " + posnetObj.GetXMLRequest() + "\n\n";

                WriteResponseParamToEventView(posnetObj);
                if (result)
                {
                    this.EventView += "XML Response : " + posnetObj.GetXMLResponse() + "\n\n";
                }
            }

            //Asecco Group
            if (aPos.PosGroup == 1)
            {
                //   String clientId = "400100000";  //Banka tarafından mağazaya verilen iş yeri numarası
                String amount = Amount.ToString();         //İşlem tutarı
                String amountWithDot = Amount.ToString().Replace(",", ".");
                String oid = OrderId;                //Sipariş numarası         
                String rnd = DateTime.Now.ToString();        //Güvenlik ve kontrol amaçlı tarih yada sürekli değişen bir değer


                String storekey = aPos.TerminalId; // "123456";                    //işyeri anahtarı
                String storetype = "3d";
                String hashstr = strMerchantID + oid + amountWithDot + successURL + failURL + rnd + storekey;
                System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                byte[] hashbytes = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(hashstr);
                byte[] inputbytes = sha.ComputeHash(hashbytes);

                String hash = Convert.ToBase64String(inputbytes);   //Günvelik amaçlı oluşturulan hash


                formStr = " <form id=\"form1\" name=\"form1\" method=\"post\" action='" + aPos.ApiUrl3D + "'>";
                formStr += "<input type=\"hidden\" name=\"clientid\" value='" + strMerchantID + "' />";
                formStr += "<input type=\"hidden\" name=\"pan\" value='" + CCNumber + "' />";
                formStr += "<input type=\"hidden\" name=\"cv2\" value='" + CVV + "' />";
                formStr += "<input type=\"hidden\" name=\"Ecom_Payment_Card_ExpDate_Year\" value='" + strExpireYear2 + "' />";
                formStr += "<input type=\"hidden\" name=\"Ecom_Payment_Card_ExpDate_Month\" value='" + strExpireMonth + "' />";
                formStr += "<input type=\"hidden\" name=\"amount\" value='" + amountWithDot + "' />";

                formStr += "<input type=\"hidden\" name=\"oid\" value='" + oid + "' />";

                formStr += "<input type=\"hidden\" name=\"rnd\" value='" + rnd + "'/>";
                formStr += "<input type=\"hidden\" name=\"storetype\" value=\"3d\">";
                formStr += "<input type=\"hidden\" name=\"cardType\" value=\"1\">";
                formStr += "<input type=\"hidden\" name=\"lang\" value=\"tr\">";
                formStr += "<input type=\"hidden\" name=\"currency\" value=\"949\">";
                formStr += "<input type=\"hidden\" name=\"hash\" value='" + hash + "'>";

                formStr += " <input type=\"hidden\" name=\"okUrl\" value='" + successURL + "'>";
                formStr += "<input type=\"hidden\" name=\"failUrl\" value='" + failURL + "'>";
                formStr += "<noscript>";
                formStr += "<h4>Odeme islemine otomatik olarak devam edilmemesi durumunda DEVAM i tiklayiniz.</h4>";
                formStr += "<input type=\"submit\" value=\"DEVAM\" /><br />";
                formStr += "</noscript>";
                formStr += "</form>";
                formStr += "<script>";
                formStr += "document.form1.submit();";
                formStr += "</script>";
            }
            else
            {
                formStr = formStr.Replace("{PostUrl}", aPos.ApiUrl3D).Replace("{SessionId}", SessionId);
                formStr = formStr.Replace("{SuccessUrl}", successURL).Replace("{FailUrl}", failURL);
                formStr = formStr.Replace("{TimeStamp}", TimeStamp).Replace("{Summary}", strSummary);
                formStr = formStr.Replace("{Mode}", strMode).Replace("{Version}", strVersion);
                formStr = formStr.Replace("{HashData}", HashData).Replace("{UserID}", strUserID).Replace("{MerchantID}", strMerchantID);
                formStr = formStr.Replace("{IPAddress}", strIPAddress).Replace("{EmailAddress}", strEmailAddress).Replace("{CardNumber}", CCNumber);
                formStr = formStr.Replace("{ExpireDate}", strExpireDate).Replace("{CVV2}", CVV).Replace("{OrderID}", OrderId);
                formStr = formStr.Replace("{Installment}", strInstallmentCount).Replace("{InstallmentZero}", strInstallmentCountZero).Replace("{InstallmentSpace}", strInstallmentCountSpace).Replace("{InstallmentDouble}", strInstallmentDouble);
                formStr = formStr.Replace("{Amount}", strAmount).Replace("{AmountWithDot}", strAmountWithDot).Replace("{Amount12}", strAmount12);
                formStr = formStr.Replace("{CurrencyCode}", strCurrencyCode).Replace("{CardholderPresentCode}", strCardholderPresentCode);
                formStr = formStr.Replace("{TerminalID}", strTerminalID).Replace("{APIPass}", aPos.ApiPass).Replace("{CardType}", "VISA").Replace("{APIUser}", aPos.ApiUserName);
                formStr = formStr.Replace("{ExpireYear4}", ExpYear.ToString()).Replace("{ExpireMonth}", strExpireMonth);
                formStr = formStr.Replace("{ExpireYear2}", strExpireYear2);
                formStr = formStr.Replace("{CompanyAddress}", "").Replace("{CompanyCity}", "").Replace("{CompanyPostalCode}", "").Replace("{Phone}", "");
                formStr = formStr.Replace("{City}", "").Replace("{PostalCode}", "").Replace("{Address}", "").Replace("{CompanyName}", "").Replace("{Name}", "");
            }

            #endregion

            return formStr;
        }



        string EventView;
        private void WriteResponseParamToEventView(C_Posnet posnetObj)
        {

            this.EventView += ("Approved Code : " + posnetObj.GetApprovedCode() + "\n");

            if (posnetObj.GetResponseCode().Length > 0)
            {
                this.EventView += ("Error Code : " + posnetObj.GetResponseCode() + "\n");
            }

        }
        #endregion
    }

    #endregion

    public class PosProcess
    {
        #region GetPos

        public static Pos GetPos(int id)
        {
            Pos pos = new Pos();
            pos = Parameters.PosList.Where(p => p.PosId == id).FirstOrDefault();
            return pos;
        }

        #endregion

        #region Calculate

        //public static Pos Calculate(int id, decimal price, decimal taxincludedPrice, decimal cargoPrice, decimal cargoListPrice)
        //{
        //    Pos pos = new Pos();
        //    pos = Parameters.PosList.Where(p => p.PosId == id).FirstOrDefault();
        //    foreach (PosInstallment pi in pos.PosInstallment)
        //    {
        //        pi.TotalInterestPrice = Math.Round((pi.InstallmentNumber == 1 ? price : taxincludedPrice) * pi.CommissionRate, 2);
        //        pi.InterestPrice = Math.Round(pi.TotalInterestPrice / pi.TotalInstallment, 2);
        //    }
        //    return pos;
        //}

        #endregion

        #region CalculateAll

        //public static void CalculateAll(IList<Pos> posList, decimal price, decimal taxincludedPrice, decimal cargoPrice, decimal cargoListPrice)
        //{
        //    foreach (Pos pos in posList)
        //    {
        //        foreach (PosInstallment pi in pos.PosInstallment)
        //        {
        //            pi.TotalInterestPrice = Math.Round((pi.InstallmentNumber == 1 ? price : taxincludedPrice) * pi.CommissionRate, 2);
        //            pi.InterestPrice = Math.Round(pi.TotalInterestPrice / pi.TotalInstallment, 2);
        //        }
        //    }
        //}

        #endregion

    }
}
